package websocket

import (
	"context"
	"gitee.com/sdynasty/clever/log"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
	"sync"
)

var (
	// LOG .
	LOG = log.NewHelper(log.With(log.GetLogger(), "source", "websocket"))
)


// ServerOption is an HTTP server option.
type ServerOption func(*Server)

// WithAddress with server address.
func WithAddress(addr string) ServerOption {
	return func(s *Server) {
		s.address = addr
	}
}




// Server is an HTTP server.
type Server struct {
	*http.Server
	once     		sync.Once
	err      		error
	address  		string
}

func NewServer(addr string, processor MessageProcessor, opts ...ServerOption) *Server {
	srv := &Server{
		address: addr,
	}
	for _, o := range opts {
		o(srv)
	}
	_sessionMgr.SetProcessor(processor)
	return srv
}


func (s *Server) Start(context.Context) error {
	http.Handle("/metrics", promhttp.Handler())
	LOG.Log(log.LevelInfo, "[websocket] server listening on: %s", s.address)

	srv, err := createAcceptor(s.address)
	if err != nil {
		return err
	}

	s.Server = srv
	go _sessionMgr.StartMQ()
	return s.Server.ListenAndServe()
}

func (s *Server) Stop(ctx context.Context) error {
	LOG.Info("[websocket] server stopping")
	s.Shutdown(ctx)
	return nil
}